package context

import (
	"encoding/json"
	"time"
)

const (
	CallTypeDirect = 0 //立刻回复，不关心结果
	CallTypeOver   = 1 //执行结束, 再进行回复
)

type AppRequest struct {
	AppName  string      `json:"appName"`
	Action   int         `json:"action"`
	CallType int         `json:"callType"`
	GenTime  int         `json:"genTime"`
	Data     interface{} `json:"data"`

	funcs map[int]func(args interface{})
}

func (app *AppRequest) Decode(stream []byte) (err error) {
	err = json.Unmarshal(stream, app)
	if err != nil {
		return
	}
	if app.GenTime == 0 {
		app.GenTime = int(time.Now().Unix())
	}
	return
}

const (
	EventTaskReady = iota
	EventTaskBuffer
	EventTaskStart
	EventTaskSuccess
	EventTaskFail
)

func (app *AppRequest) AddEvent(event int, f func(args interface{})) {
	if app.funcs == nil {
		app.funcs = make(map[int]func(args interface{}))
	}
	app.funcs[event] = f
}

func (app *AppRequest) GetEvent(event int) func(args interface{}) {
	if app.funcs != nil {
		if f, ok := app.funcs[event]; ok {
			return f
		}
	}
	return nil
}
